/**
 * 像素战争配置信息
 * @param backgroundColor 画布底色
 * @param boxSize 画布每个格子的大小，单位像素
 * @param boxMargin boxSize表示的涂抹颜色的大小，为了和相邻的box隔开，中间需要有空白；
 * 想象一个大的box套在一个小的box上面，大的box彼此相连，boxMargin代表的是小box到大box的距离；
 * @constructor
 */
function ChaosConfig(backgroundColor, boxSize, boxMargin) {
    this.backgroundColor = backgroundColor || "#e8e8e8";
    this.boxSize = boxSize || 6;
    this.boxMargin = boxMargin || 0.5;
    this.canvasId = 1;
    this.actualBoxSize = this.boxSize + this.boxMargin * 2;
}

/**
 * 像素战争的主类
 * @param chaosConfig 一个{@link ChaosConfig}配置信息
 * @constructor
 */
function Chaos(chaosConfig) {
    /**
     * 配置信息
     * @type {ChaosConfig}
     */
    this.chaosConfig = chaosConfig || new ChaosConfig();

    /**
     * 加载的初始化画布数据
     * @type {[]}
     */
    this.initData = [];

    /**
     * 画布
     * @type {{}}
     */
    this.canvas = {};
    this.cvs = {};

    /**
     * WebSocket客户端
     * @type {{}}
     */
    this.stompClient = {};

    /**
     * 加载loading特效索引，供关闭时用
     * @type {{}}
     */
    // this.loadAnimationIndex = {};

    /**
     * 获取当前活动的画布ID
     */
    this.loadCanvasId = function () {
        this.chaosConfig.canvasId = sessionStorage.getItem("canvasId");
    }

    /**
     * 调用接口加载画布数据
     */
    this.loading = function () {

        // 先判断用户是否登录了
        let token = getLoginToken();
        if (null == token || "" === token) {
            layer.msg("请登录", {
                time: 1000
            }, function () {
                window.location.href = "../chaos/login.html";
            });
        } else {
            // this.loadAnimationIndex = layer.load();

            // 加载画布ID
            this.loadCanvasId();
            let url = "/chaos/api/play/canvas/" + this.chaosConfig.canvasId;
            let that = this;
            $.ajax({
                async: false,
                method: 'get',
                headers: {
                    'token': getLoginToken(),
                    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
                },
                url: url,
                success: function (res) {
                    ensureLogin(res);
                    if (res.code !== 1000) {
                        layer.msg("哎呀卧槽，出BUG了，去聊天室看看",
                            {
                                icon: 5,
                                time: 1000
                            },
                            function () {
                                alert("假装跳到了聊天室");
                            });
                    } else {
                        // 使用隐藏的img和canvas获取到字节数组
                        let img = document.getElementById("imgHelper");
                        img.src = "data:;base64," + res.body;
                        console.log("LoadCanvas: src=" + img.src);

                        // 必须等待画布初始图片加载完毕才能进行后续逻辑
                        img.onload = function () {
                            that.loadInitData();
                            that.init();
                            that.fillBackground();
                            that.fillInitImage();
                            that.click();
                            that.socketConnect();
                            // layer.close(that.loadAnimationIndex);
                        }
                    }
                },
                error: function (err) {
                    // 需要加入处理
                    layer.msg("哎呀卧槽，出BUG了，去聊天室看看",
                        {
                            icon: 5,
                            time: 1000
                        },
                        function () {
                            alert("假装跳到了聊天室");
                        });
                }
            });
        }
    }

    /**
     * 从图片中加载RGB数组
     */
    this.loadInitData = function () {

        let img = document.getElementById("imgHelper");
        let w = img.width, h = img.height;
        console.log("LoadCanvas: 初始化图片宽" + w + ", 高" + h);
        let hiddenCanvas = document.createElement("canvas");
        hiddenCanvas.width = w;
        hiddenCanvas.height = h;
        let ctx = hiddenCanvas.getContext("2d");
        ctx.drawImage(img, 0, 0);
        let imgData = ctx.getImageData(0, 0, w, h).data;

        let pos = 0;
        this.initData = [];
        for (let i = 0; i < h; i++) {
            this.initData[i] = [];
            for (let j = 0; j < w; j++) {
                let pixelRgb = "rgb(" + imgData[pos] + "," + imgData[pos + 1] + "," + imgData[pos + 2] + ")";
                pos += 4;
                this.initData[i][j] = pixelRgb;
            }
        }
    }

    /**
     * 初始化画布
     */
    this.init = function () {
        let canvas = document.querySelector("#chaosCanvas");
        let width = this.chaosConfig.actualBoxSize * this.initData[0].length + "";
        let height = this.chaosConfig.actualBoxSize * this.initData.length + "";
        console.log("Init: 画布宽" + width + ",高" + height);
        canvas.setAttribute("width", width);
        canvas.setAttribute("height", height);
        let down = document.querySelector(".down");
        down.onclick = function () {
            download(canvas.toDataURL(), 'test.png', 'image/png')
        }
        this.canvas = canvas;
        this.cvs = this.canvas.getContext("2d");
        sessionStorage.setItem("selectColor", "#000000")
    }

    /**
     * 画布涂抹底色
     */
    this.fillBackground = function () {
        this.cvs.beginPath();
        this.cvs.fillStyle = this.chaosConfig.backgroundColor;
        this.cvs.fillRect(0, 0, this.canvas.width, this.canvas.height);
        this.cvs.fill();
        this.cvs.stroke();
        this.cvs.closePath();
    }

    /**
     * 给纵向第hPos，横向第wPos个box涂上颜色color
     * @param hPos box纵向序号
     * @param wPos box横向序号
     * @param color 涂抹的颜色
     */
    this.drawBox = function (hPos, wPos, color) {
        this.cvs.beginPath();
        this.cvs.fillStyle = color;
        this.cvs.fillRect(this.chaosConfig.actualBoxSize * wPos + 1, this.chaosConfig.actualBoxSize * hPos + 1, this.chaosConfig.boxSize, this.chaosConfig.boxSize);
        this.cvs.fill();
        this.cvs.stroke();
        this.cvs.closePath();
    }

    /**
     * 将初始化的图片加载到canvas画布上
     */
    this.fillInitImage = function () {
        for (let i = 0; i < this.initData.length; i++) {
            for (let j = 0; j < this.initData[i].length; j++) {
                const element = this.initData[i][j];
                this.drawBox(i, j, element);
            }
        }
    }

    /**
     * 绑定点击事件
     */
    this.click = function () {
        this.canvas.addEventListener("mousedown", function (e) {
            let wPos = parseInt(e.offsetX / this.chaosConfig.actualBoxSize);
            let hPos = parseInt(e.offsetY / this.chaosConfig.actualBoxSize);
            this.updatePixel(hPos, wPos, getSelectedColor());
        }.bind(this));
    }

    /**
     * 点击事件调用的更新像素位的方法
     * @param hPos
     * @param wPos
     * @param color
     */
    this.updatePixel = function (hPos, wPos, color) {
        let url = "/chaos/api/play/canvas/pixel";
        let that = this;
        $.ajax({
            method: 'put',
            headers: {
                'token': getLoginToken()
            },
            contentType: "application/json",
            data: JSON.stringify({
                "canvasId": this.chaosConfig.canvasId,
                "colorRgbHex": color,
                "hpos": hPos,
                "wpos": wPos
            }),
            dataType: "json",
            url: url,
            success: function (res) {
                ensureLogin(res);
                if (res.code !== 1000) {
                    layer.msg(res.message, {time: 500});
                } else {
                    that.drawBox(hPos, wPos, color);
                }
            },
            error: function (err) {
                console.log("err");
            }
        });
    }

    /**
     * WebSocket连接
     */
    this.socketConnect = function () {
        let that = this;
        // stomp配置信息
        const stompConfig = {
            // brokerURL: "ws://pixelgear.top/chaos/canvas-update-notice-websocket",
            // 域名暂时没有完成备案，先通过IP
            brokerURL: "ws://106.12.181.80/chaos/canvas-update-notice-websocket",
            debug: function (str) {
                console.log("STOMP: " + str);
            },

            // 断连后200ms自动重连
            reconnectDelay: 200,
            heartbeatIncoming: 4000,
            heartbeatOutgoing: 4000,

            onConnect: function (frame) {
                that.stompClient.subscribe("/topic/update-notice", function (message) {
                    const payload = JSON.parse(message.body);
                    that.handleNotice(payload);
                });
            }
        };

        // 创建客户端实例
        this.stompClient = new StompJs.Client(stompConfig);
        this.stompClient.activate();
    }

    /**
     * 处理更新像素点的通知
     * @param notice
     */
    this.handleNotice = function (notice) {
        let hPos = notice.hpos;
        let wPos = notice.wpos;
        let color = notice.colorRgbHex;
        this.drawBox(hPos, wPos, color);
    }
}


function getSelectedColor() {
    return sessionStorage.getItem("selectColor");
}

/**
 * 改变颜色的事件
 */
function changeColor() {
    let color = document.getElementById("color");
    sessionStorage.setItem("selectColor", color.value);
}

let loadAnimationIndex = layer.load();

chaos = new Chaos();
chaos.loading();


layer.close(loadAnimationIndex);